package com.xjscrm.console.chat.mq;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @author mingyang.chen create in 2024/2/28 10:44
 */
@Slf4j
@Component
public class MQSender implements ApplicationContextAware {

    private static RocketMQTemplate rocketMQTemplate;

    public static void sendMQMsg(String topic, Object data) {
        rocketMQTemplate.asyncSend(topic, MessageBuilder.withPayload(data).build(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("MQ发送成功. msg:{}", JSON.toJSONString(data));
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("MQ发送失败", throwable);
            }
        });
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        rocketMQTemplate = applicationContext.getBean(RocketMQTemplate.class);
    }
}
